//
//  EditMobileViewController.m
//  YiBaoStore
//
//  Created by 吕清毅 on 2018/10/4.
//  Copyright © 2018年 小河. All rights reserved.
//

#import "EditMobileViewController.h"

@interface EditMobileViewController ()<UITextFieldDelegate>

@property (nonatomic, strong) UITextField *phoneTF;
@property (nonatomic, strong) UIButton *editBtn;
@end

@implementation EditMobileViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setNaviWith:@"更改手机号"];
    [self setMainView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(TextFieldChange) name:UITextFieldTextDidChangeNotification object:nil];
}

- (void)setMainView
{
    UIView *headView = [UIView new];
    if (@available(iOS 11.0, *)) {
        headView.frame = CGRectMake(0, TopBarHeight_xs, SCREENWIDTH, 44);
    } else {
        // Fallback on earlier versions
        headView.frame = CGRectMake(0, TopBarHeight, SCREENWIDTH, 44);
    }
    headView.backgroundColor = HexWithAlpha(0xF0F0F0, 0.53);
    [self.view addSubview:headView];
    
    UIImageView *leftIV = [UIImageView new];
    leftIV.frame = CGRectMake(15, 15, 14, 14);
    leftIV.image = [UIImage imageNamed:@"nowMobile"];
    [headView addSubview:leftIV];
    
    UILabel *mobileLab = [UILabel new];
    mobileLab.frame = CGRectMake(leftIV.right+15, 11, 180, 21);
    mobileLab.textColor = UIColorFromHex(0x9E9E9E);
    mobileLab.font = FontSemiboldSize(14);
    mobileLab.text = [NSString stringWithFormat:@"当前手机号：%@",self.mobile];
    [headView addSubview:mobileLab];
    
    UILabel *phoneLab = [UILabel new];
    phoneLab.frame = CGRectMake(15, headView.bottom+30, 55, 12);
    phoneLab.textColor = goldColor;
    phoneLab.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:12];
    phoneLab.attributedText = [TTKUtil getAtttributeStringWithLineSpace:0 kern:1 and:@"手机号码"];
    [self.view addSubview:phoneLab];
    
    self.phoneTF = [UITextField new];
    self.phoneTF.frame = CGRectMake(phoneLab.left, phoneLab.bottom+10, SCREENWIDTH-30, 16);
    self.phoneTF.delegate = self;
    //self.phoneTF.secureTextEntry = YES;
    self.phoneTF.keyboardType = UIKeyboardTypeNumberPad;
    self.phoneTF.returnKeyType = UIReturnKeyNext;
    self.phoneTF.textColor = titleColor;
    UIButton *button = [self.phoneTF valueForKey:@"_clearButton"];
    [button setImage:[UIImage imageNamed:@"delete"] forState:UIControlStateNormal];
    self.phoneTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.phoneTF.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:16];
    self.phoneTF.placeholder = @"请输入手机号码";
    [self.phoneTF setValue:UIColorFromHex(0xD8D8D8) forKeyPath:@"_placeholderLabel.textColor"];
    //[self.phoneTF setValue:[UIColor colorWithRed:208/255.0 green:208/255.0 blue:210/255.0 alpha:0.3] forKeyPath:@"_placeholderLabel.textColor"];
    [self.phoneTF setValue:FontWithSize(16) forKeyPath:@"_placeholderLabel.font"];
    [self.view addSubview:self.phoneTF];
    
    UIView *lineView = [UIView new];
    lineView.frame = CGRectMake(phoneLab.left, _phoneTF.bottom+10, SCREENWIDTH-30, 1);
    lineView.backgroundColor = BacklineColor;
    [self.view addSubview:lineView];
    
    self.editBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.editBtn.frame = CGRectMake(2*leftPadding, lineView.bottom+60, SCREENWIDTH-80, 50);
    self.editBtn.layer.cornerRadius = 20;
    self.editBtn.layer.masksToBounds = YES;
    self.editBtn.backgroundColor = goldColor;
    [self.editBtn setTitleColor:titleColor forState:UIControlStateNormal];
    self.editBtn.titleLabel.font = FontWithSize(18);
    //self.editBtn.backgroundColor = UIColorFromHex(0xD1D1D1);
    //[self.editBtn setTitleColor:UIColorFromHex(0x8D8D8D) forState:UIControlStateNormal];
    [self.editBtn setTitle:@"确认修改" forState:UIControlStateNormal];
    [self.editBtn addTarget:self action:@selector(editClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.editBtn];
}

- (void)TextFieldChange
{
    NSString *phone = self.phoneTF.text;
    if (phone.length > 11) {
        phone = [phone substringToIndex:11];
    }
    if (phone.length>0) {
        self.phoneTF.attributedText = [TTKUtil getAtttributeStringColorWithLineSpace:0 kern:1.33 and:phone];
        self.phoneTF.textColor = titleColor;
    }
}
#pragma mark -- 验证码
- (void)getCode:(UIButton *)btn
{
    NSString *phone = self.phoneTF.text;
    if([phone isEqualToString:@""])
    {
        [TTKUtil hudShowMessage:@"请输入手机号码"];
        return;
    }
    if (![TTKStringUtils isValidateMobile:phone])
    {
        [TTKUtil hudShowMessage:@"请输入正确的手机号码"];
        return;
    }
    
    NSMutableDictionary *data = [NSMutableDictionary dictionary];
    [data setValue:self.phoneTF.text forKey:@"mobile"];
    [HttpRequest formPostPath:GetVerifyCode_API params:data resultBlock:^(id Data, MsgModel *msgModel) {
        [self ShowHUDWithMessage:@"验证码发送成功"];
    }];
    
    [self startCodeBtnTimeWithBtn:btn];
}

#pragma mark -- 获取验证码
- (void)startCodeBtnTimeWithBtn:(UIButton *)btn
{
    __block int timeout = 59; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        NSString *title = @"重新发送";
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [btn setAttributedTitle:[TTKUtil getAtttributeStringColorWithLineSpace:0 kern:1.33 and:title] forState:UIControlStateNormal];
                btn.userInteractionEnabled = YES;
            });
        }else{
            int seconds = timeout %60 ;
            NSString *name = @"重新发送";
            NSString *strTime = [NSString stringWithFormat:@"%@%d",name,seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [btn setAttributedTitle:[TTKUtil getAtttributeStringColorWithLineSpace:0 kern:1.33 and:strTime] forState:UIControlStateNormal];
                btn.userInteractionEnabled = NO;
            });
            timeout--;
        }
    });
    
    dispatch_resume(_timer);
}

#pragma mark -- 修改
- (void)editClick:(UIButton *)btn
{
    if (self.phoneTF.text.length == 0) {
        [self ShowHUDWithMessage:@"店主手机号不能为空"];
        return;
    }
    if (self.phoneTF.text.length != 11) {
        [self ShowHUDWithMessage:@"手机号格式错误"];
        return;
    }
    NSMutableDictionary *data = [NSMutableDictionary dictionary];
    [data setValue:[NSNumber numberWithInteger:self.id] forKey:@"id"];
    [data setValue:self.phoneTF.text forKey:@"ownerMobile"];
    [HttpRequest formPostPath:EditMyInfo_API params:data resultBlock:^(id Data, MsgModel *msgModel) {
        [self ShowHUDWithMessage:@"修改成功"];
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
}

@end
